<script setup lang="ts">
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { Card } from 'ant-design-vue';
  import { PageWrapper } from '@/components/Page';
  import { ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { formSchema } from '../util/gateway.data';
  import { addOrUpdate } from '@/api/system/gateway';
  import RouterConfigTable from '@/views/system/gateway/drawer/RouterConfigTable.vue';

  const tableRef = ref<{ getDataSource: () => any; setTableData: () => any } | null>(null);
  const filtersRef = ref<{ getDataSource: () => any; setTableData: () => any } | null>(null);
  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const filters = ref('filters');
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 90,
    baseColProps: { span: 12 },
    schemas: formSchema,
    showActionButtonGroup: false,
  });
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      tableRef.value.setTableData(data.record.predicatesConfig);
      filtersRef.value.setTableData(data.record.filtersConfig);
      setFieldsValue({
        ...data.record,
      });
    } else {
      tableRef.value.setTableData([]);
      filtersRef.value.setTableData([]);
    }
  });
  const getTitle = computed(() => (!unref(isUpdate) ? '新增路由' : '编辑路由'));

  async function handleSubmit() {
    try {
      const values = await validate();
      if (tableRef.value) {
        values.predicatesConfig = tableRef.value.getDataSource();
      }
      if (filtersRef.value) {
        values.filtersConfig = filtersRef.value.getDataSource();
      }
      values.update = unref(isUpdate);
      setDrawerProps({ confirmLoading: true });
      await addOrUpdate(values);
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>

<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="70%"
    @ok="handleSubmit"
  >
    <PageWrapper>
      <Card title="基本信息" :bordered="false">
        <BasicForm @register="registerForm" />
      </Card>
      <Card title="断言配置" :bordered="false">
        <RouterConfigTable ref="tableRef" :router-update="isUpdate" />
      </Card>
      <Card title="过滤配置" :bordered="false">
        <router-config-table ref="filtersRef" :router-update="isUpdate" :config-type="filters" />
      </Card>
    </PageWrapper>
  </BasicDrawer>
</template>
